var uuidV4 = require('uuid/v4');
var Eventproxy = require('eventproxy');
var logger = require('../common/logger');
var models = require('../models');
var tools = require('../common/tools');
var config = require('config-lite');

exports.getUsers = function getUsers(req, res, next) {
  var reqQuery = req.query;
  var page = parseInt(reqQuery.page, 10) || 1;
  page = page > 0 ? page : 1;
  var limit = models.user.pageLimit(Number(reqQuery.limit));
  var offset = models.user.pageOffset(page, limit);

  var condition = {
    offset: offset,
    limit: limit,
    where: {}
  };

  var user = req.user;
  if (user.plevel === config.plevels[0]) {
    condition.where['$or'] =  [{
      'event_uuid': null
    }, {
      '$event.status$': 1
    }];
    condition.include = [{
      // where: models.sequelize.literal('`event` IS null'),
      model: models.event,
      // where: {
      //   $or: [{
      //     uuid: null
      //   }, {
      //     status: 1
      //   }]
      // }
    }];
  }

  if (user.event_uuid) {
    condition.where.event_uuid = user.event_uuid;
  }

  models.user.findAndCountAll(condition).then(function(returnUsers) {
    return res.send_data({
      entities: returnUsers.rows,
      total_pages: models.user.totalPages(returnUsers.count, limit),
      current_page: page
    })
  });
};

exports.getUserByUUID = function getUserByUUID(req, res) {
  var userUUID = req.params.uuid;

  models.user.findOne({
    where: {
      uuid: userUUID
    }
  }).then(function(returnUser) {
    return res.send_data({
      entities: returnUser
    });
  });
};

exports.newUser = function newUser(req, res, next) {
  var ep = new Eventproxy();
  ep.fail(next);
  var data = req.body;
  logger.info(data);

  var user = req.user;

  var userId = req.params.uuid;

  ep.all('missing', function (attrs) {
    if (attrs.length) {
      return res.send_data({
        code: 400,
        message: '缺少字段' + attrs
      });
    }
  });
  var missingAttrs = tools.checkMissingAttr(data, ['name', 'plevel', 'pcode']);
  if (missingAttrs.length) {
    return ep.emit('missing', missingAttrs);
  }

  if (data.plevel !== config.plevels[0] && !data.event_uuid) {
    return ep.emit('missing', ['event_uuid']);
  }

  data.pcode += '';
  data.name = data.name.trim();
  data.pcode = data.pcode.trim();

  if (config.plevels.indexOf(data.plevel) < 0) {
    return res.send_data({
      code: 400,
      message: 'plevel值不对'
    });
  }

  if (user.plevel !== config.plevels[0] && data.plevel === config.plevels[0]) {
    return res.send_data({
      code: 400,
      message: '没有权限创建该plevel的用户'
    });
  }

  // if (user.plevel === config.plevels[0] && (data.plevel !== config.plevels[0] && data.plevel !== config.plevels[1])) {
  //   return res.send_data({
  //     code: 400,
  //     message: '没有权限创建该plevel的用户，系统管理员只能创建系统管理员和各赛事的赛事管理员'
  //   });
  // }

  var eventId = user.event_uuid;
  models.user.findOne({
    where: {
      pcode: data.pcode
    }
  }).then(function(returnUser) {
    if (userId) { // 编辑
      if (returnUser && returnUser.uuid !== userId) {
        return res.send_data({
          code: 400,
          message: '已存在相同的pcode，请重新生成pcode'
        });
      }
      models.user.update(data, {
        where: {
          uuid: userId
        }
      }).then(function(returnData) {
        return res.send_data();
      });
    } else {
      if (returnUser) {
        return res.send_data({
          code: 400,
          message: '已存在相同的pcode，请重新生成pcode'
        });
      }
      data.event_uuid = data.plevel === config.plevels[0] ? null : data.event_uuid;
      models.user.create(data).then(function(returnData) {
        return res.send_data();
      });
    }
  });
};

exports.genPcode = function genPcode(req, res) {
  tools.genPcode(function (pcode) {
    return res.send_data({
      entities: [{
        pcode: pcode
      }]
    });
  });
};

exports.delUser = function delUser(req, res) {
  var data = req.body;

  var userId = req.params.uuid;

  models.user.destroy({
    where: {
      uuid: userId
    }
  }).then(function() {
    return res.send_data();
  });
};

exports.enableUser = function enableUser(req, res) {
  var data = req.body;

  var userId = req.params.uuid;

  models.user.update({
    status: 1
  }, {
    where: {
      uuid: userId
    }
  }).then(function() {
    return res.send_data();
  });
};

exports.disableUser = function disableUser(req, res) {
  var data = req.body;

  var userId = req.params.uuid;

  models.user.update({
    status: 0
  }, {
    where: {
      uuid: userId
    }
  }).then(function() {
    return res.send_data();
  });
};
